package cn.com.mrzheng.web.controller;

import cn.com.mrzheng.web.entity.Post;
import cn.com.mrzheng.web.server.interfaces.IPostServer;
import cn.com.mrzheng.web.utils.Envelope;
import cn.com.mrzheng.web.utils.ServiceApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

// rest风格控制器
@RestController
//  跨域调用
@CrossOrigin(origins = ServiceApi.Config.CrossOrigin, maxAge = 3600)
public class PostController {

    @Autowired
    IPostServer PostServer;

    // 添加
    @RequestMapping(value = ServiceApi.Post.ADD, method = RequestMethod.POST)
    public String add(String title, String content, String author, String time){
        Post post = new Post(title, content, author, time);
        String state = PostServer.add(post);
        return state;
    }

    // 删除
    @RequestMapping(value = ServiceApi.Post.DELETE, method = RequestMethod.POST)
    public String delete(String id){
        String state = PostServer.delete(id);
        return state;
    }

    // 更新文章
    @RequestMapping(value = ServiceApi.Post.UPDATE, method = RequestMethod.POST)
    public String update(String id,String title, String content, String author, String time){
        Post post = new Post(title, content, author, time);
        post.setPostId(Integer.parseInt(id));
        String state = PostServer.update(post);
        return state;
    }

    // 获取列表
    @RequestMapping(value = ServiceApi.Post.LIST, method = RequestMethod.GET)
    public Envelope list(String author, String currentPage, String pageSize){
        List<Post> posts = null;
        List<Post> total = null;
        total = PostServer.List();
        int totalSize = total.size();
        if (author.isEmpty()) {
            posts = PostServer.List(Integer.parseInt(currentPage), Integer.parseInt(pageSize));
        } else {
            posts = PostServer.listByAuthor(author, Integer.parseInt(currentPage), Integer.parseInt(pageSize));
        }
        Envelope<Post> envelope = new Envelope<>();
        envelope.setTotal(totalSize);
        envelope.setData(posts);
        return envelope;
    }
}
